package com.sjtu.rest;

import com.sjtu.dao.model.ClientInfo;
import com.sjtu.dao.model.UserAccount;
import com.sjtu.dao.repository.ClientInfoRepository;
import com.sjtu.dao.repository.UserAccountRepository;
import com.sjtu.feign.UserAccountFeign;
import com.sjtu.util.JpaUtil;
import com.sjtu.web.BaseRest;
import com.sjtu.web.Result;
import com.sjtu.web.form.UserAccountForm;
import com.sjtu.web.form.UserAccountResetPwdForm;
import com.sjtu.web.search.UserAccountSearch;
import com.sjtu.web.vo.ClientInfoVo;
import com.sjtu.web.vo.UserAccountVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;
import java.util.stream.Collectors;

/**
 * nerine
 * 2/4/2020
 */
@Slf4j
@RequestMapping(UserAccountFeign.PREFIX)
@RestController
public class UserAccountRest extends BaseRest {

    @Autowired
    private UserAccountRepository userAccountRepository;
    @Autowired
    private ClientInfoRepository clientInfoRepository;

    @PostMapping("/list")
    public Result<?> list(@RequestBody UserAccountSearch search) {
        UserAccount userAccount = new UserAccount();
        if(StringUtils.isNoneBlank(search.getSystemId())) {
            ClientInfo clientInfo = new ClientInfo();
            clientInfo.setSystemId(search.getSystemId());
            clientInfo = clientInfoRepository.findOne(Example.of(clientInfo)).get();
            userAccount.setClientInfo(clientInfo);
        }
        Page<UserAccount> result = userAccountRepository.findAll(
                Example.of(userAccount),
                PageRequest.of(search.getCurrent(), search.getSize(), Sort.by(Sort.Direction.DESC, "createdDate"))
        );
        List<UserAccountVo> voList = result.stream().map(e -> {
            UserAccountVo vo = new UserAccountVo();
            vo.setIdUserAccount(e.getIdUserAccount());
            vo.setUserId(e.getUserId());
            vo.setUserName(e.getUserName());
            vo.setPassword(e.getPassword());
            vo.setRole(e.getRole());
            vo.setClientInfo(createClientInfoVo(e));
            vo.setCreatedDate(e.getCreatedDate());
            return vo;
        }).collect(Collectors.toList());
        return success(voList);
    }

    private ClientInfoVo createClientInfoVo(UserAccount userAccount) {
        ClientInfoVo clientInfoVo = new ClientInfoVo();
        if(userAccount.getClientInfo() != null) {
            clientInfoVo.setIdClientInfo(userAccount.getClientInfo().getIdClientInfo());
            clientInfoVo.setSystemId(userAccount.getClientInfo().getSystemId());
            clientInfoVo.setSystemName(userAccount.getClientInfo().getSystemName());
            clientInfoVo.setInstances(userAccount.getClientInfo().getInstances());
        }
        return clientInfoVo;
    }

    @GetMapping("/detail/{id}")
    public Result<UserAccountVo> detail(@PathVariable String id) {
        UserAccount userAccount = userAccountRepository.findById(id).get();
        //回显不展示该字段
        userAccount.setPassword(null);
        return success(toVo(userAccount));
    }

    UserAccountVo toVo(UserAccount userAccount) {
        UserAccountVo vo = new UserAccountVo();
        vo.setIdUserAccount(userAccount.getIdUserAccount());
        vo.setUserId(userAccount.getUserId());
        vo.setUserName(userAccount.getUserName());
        vo.setPassword(userAccount.getPassword());
        vo.setRole(userAccount.getRole());
        vo.setClientInfo(createClientInfoVo(userAccount));
        vo.setCreatedDate(userAccount.getCreatedDate());
        return vo;
    }

    @GetMapping("/find-by-user-id")
    public Result<UserAccountVo> findByUserId(@RequestParam String userId) {
        UserAccount userAccount = new UserAccount();
        userAccount.setUserId(userId);
        userAccount = userAccountRepository.findOne(Example.of(userAccount)).orElse(new UserAccount());

        UserAccountVo vo = toVo(userAccount);
        log.info("get user: {}", vo);
        return success(vo);
    }

    @PostMapping("/save")
    public Result<?> save(@RequestBody UserAccountForm form) {
        ClientInfo clientInfo = new ClientInfo();
        clientInfo.setSystemId(form.getSystemId());
        clientInfo = clientInfoRepository.findOne(Example.of(clientInfo)).get();

        UserAccount userAccount = new UserAccount();
        userAccount.setUserId(form.getUserId());
        userAccount = userAccountRepository.findOne(Example.of(userAccount)).orElse(new UserAccount());

        userAccount.setUserId(form.getUserId());
        userAccount.setRole(form.getRole());
        userAccount.setUserName(form.getUserName());
        userAccount.setClientInfo(clientInfo);
        userAccount.setPassword(form.getPassword());

        JpaUtil.setModifyInfo(form.getOperatorId(), userAccount);

        return success(userAccountRepository.save(userAccount));
    }

    @PostMapping("/reset-pwd")
    public Result<?> resetPwd(@RequestBody @Valid UserAccountResetPwdForm form) {
        UserAccount userAccount = userAccountRepository.findById(form.getIdUserAccount()).get();
        userAccount.setPassword(form.getPassword());
        userAccountRepository.save(userAccount);
        return success();
    }
}
